<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class  Gosu_Service {
	private $username = 'cuuamchankinh';
	private $password = 'S0cIy3NlB2XOLMR::vx6eSUZOqiz5jNqNdUkWHQbHOXsM=eycDAq5knQ';
	private $wsdl 	  = "http://ws.gosu.vn/gosuAccount.asmx?wsdl";
	
	private $client = NULL;

	function __construct(){
		$this->client = @new SoapClient($this->wsdl);
	}

	public function init($para = array()){
		if(!empty($para)){
			foreach($para as $key => $value){
				$this->{$key} = $value;
			}
		}
		$this->client = @new SoapClient($this->wsdl);
	}

	public function quick_register($username, $password, $email, $ip){		
		$result = $this->client->QuickRegister(array(
				"UserName"			=> $username,
				"Password"			=> $password,
				"Email"				=> $email,
				"IP"				=> $ip,
				"wsUserName"		=> $this->username,
				"Signature"			=> md5($username.$ip.$this->username.$this->password)
		));
		
		return $result->QuickRegisterResult;
	}
	
	public function validate_username($username) {
		$result = $this->client->ValidateUserName(array(
				"UserName"			=> $username,
				"wsUserName"		=> $this->username,
				"Signature" 		=> md5($this->username.$this->password)			
		));
		
		return $result->ValidateUserNameResult;
	}
	
	public function validate_email($email) {
		$result = $this->client->ValidateEmail(array(
				"Email"				=> $email,
				"wsUserName"		=> $this->username,
				"Signature" 		=> md5($this->username.$this->password)			
		));
		
		return $result->ValidateEmailResult;
	}
	
	public function link_to_game($server, $username, $client_ip) {
		$time = time();
		$url = 'https://id.gosu.vn/game/LinkToGame';
		$data = array(
    		'server' 		=> $server,
			'username'  	=> $username,
            'time' 			=> $time,
    		'clientIP' 		=> $client_ip,
    		'wsusername'	=> $this->username,
            'signature' 	=> md5($server . $username . $time . $client_ip . $this->username . $this->password)
		);
		$query = http_build_query($data);
		$uri   = $url . '?' . $query;
		$result  = @file_get_contents($uri);
		return $result;
	}
	
	public function decrypt($input) {
		$key_seed = $this->password;
		$input = base64_decode($input);
		$key = substr(md5($key_seed), 0, 24);
		$text = mcrypt_decrypt(MCRYPT_TRIPLEDES, $key, $input, MCRYPT_MODE_ECB, '12345678');
		$block = mcrypt_get_block_size('tripledes', 'ecb');
		$packing = ord($text{strlen($text) - 1});
		if ($packing and ($packing < $block)) {
			for ($P = strlen($text) - 1; $P >= strlen($text) - $packing; $P--) {
				if (ord($text{$P}) != $packing) {
					$packing = 0;
				}
			}
		}
		$text = substr($text, 0, strlen($text) - $packing);
		return $text;
	}
	
	
}